import type { App } from 'vue';
import type { I18nOptions } from 'vue-i18n';

import { createI18n } from 'vue-i18n';
import { setHtmlPageLang, setLoadLocalePool } from './helper';
import { localeSetting, LOCALE } from '@/settings/localeSetting';
import { useLocaleStoreWithOut } from '@/store/modules/locale';

import { VxeUI, VxeGlobalI18nLocale } from 'vxe-table';

import zhCN from 'vxe-pc-ui/lib/language/zh-CN';
// import zhHK from 'vxe-pc-ui/lib/language/zh-HK';
import zhTW from 'vxe-pc-ui/lib/language/zh-TW';
// import zhMO from 'vxe-pc-ui/lib/language/zh-MO';
import enUS from 'vxe-pc-ui/lib/language/en-US';
import jaJP from 'vxe-pc-ui/lib/language/ja-JP';
// import esES from 'vxe-pc-ui/lib/language/es-ES';
// import ptBR from 'vxe-pc-ui/lib/language/pt-BR';

VxeUI.setI18n(LOCALE.ZH_CN as VxeGlobalI18nLocale, zhCN);
VxeUI.setI18n(LOCALE.ZH_TW as VxeGlobalI18nLocale, zhTW);
VxeUI.setI18n(LOCALE.EN_US as VxeGlobalI18nLocale, enUS);
VxeUI.setI18n(LOCALE.JA_JP as VxeGlobalI18nLocale, jaJP);

const { fallback, availableLocales } = localeSetting;

export let i18n: ReturnType<typeof createI18n>;

async function createI18nOptions(): Promise<I18nOptions> {
  const localeStore = useLocaleStoreWithOut();
  const locale = localeStore.getLocale;
  const defaultLocal = await import(`./lang/${locale}.ts`);
  const message = defaultLocal.default?.message ?? {};

  setHtmlPageLang(locale);
  setLoadLocalePool((loadLocalePool) => {
    loadLocalePool.push(locale);
  });

  return {
    legacy: false,
    locale,
    fallbackLocale: fallback,
    messages: {
      [locale]: message,
    },
    availableLocales: availableLocales,
    sync: true, //If you don’t want to inherit locale from global scope, you need to set sync of i18n component option to false.
    silentTranslationWarn: true, // true - warning off
    missingWarn: false,
    silentFallbackWarn: true,
  };
}

// setup i18n instance with glob
export async function setupI18n(app: App) {
  const options = await createI18nOptions();
  i18n = createI18n(options);

  app.use(i18n);
}
